<!-- eslint-disable no-console -->
<script setup lang="ts">
import dayjs from 'dayjs'
import {
  Button,
  Cascader,
  Form,
  FormItem,
  Input,
  InputSearch,
  Radio,
  RadioGroup,
  Select,
  Textarea,
} from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import {
  ReservationTempCustInfoCreate,
  ReservationTempCustInfoIndex,
} from '~/requests'
import { useTempTypeStore } from '~/stores/tempType'
import { useUserStore } from '~/stores/user'
import { useMediumTypeStore } from '~/stores/mediumType'
import { sendMarkdownMessage } from '~/requests/dintTalkBot'
import { showModal } from '~/requests/method'

defineOptions({
  name: 'IndexPage',
})

useHead({
  title: '员工推荐建档',
})

interface FormState {
  media: string[]
  RecommendEmpId: string
  Phone: string
  Sex: string
  CustName: string
  Remark: string
  TmpCustRegType: string
  CreatedBy: string
  MediaSourceType: string
  MediaSource: string
  PlanRecallEmp: string
  [key: string]: any
}

const formRules: Record<string, Rule[]> = {
  RecommendEmpId: [{ required: true, message: '请输入推荐人(员工)', trigger: 'blur' }],
  Phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  Sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  CustName: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
  media: [{ required: true, message: '请输入媒介', trigger: 'blur' }],
  TmpCustRegType: [{ required: true, message: '请输入登记类型', trigger: 'blur' }],
  CreatedBy: [{ required: true, message: '请输入登记人', trigger: 'blur' }],
}

const DEFAULT_CREATED_ID: string = 'CCFB0947F9E04117B4B1B22800B6C411'

const formState = reactive<FormState>({
  media: ['9FED1ABA850E41FBB7294D4B70E0D6D6', '50B8E89D3F324398B20991E5D037E741'],
  RecommendEmpId: DEFAULT_CREATED_ID,
  Phone: '',
  Sex: '2',
  CustName: '女士',
  Remark: '',
  MediaSourceType: '9FED1ABA850E41FBB7294D4B70E0D6D6',
  MediaSource: '50B8E89D3F324398B20991E5D037E741',
  TmpCustRegType: '5FB93FF9FDD7495DAE9AAA4600E099DB',
  PlanRecallEmp: DEFAULT_CREATED_ID,
  CreatedBy: DEFAULT_CREATED_ID,
})
const loading = ref(false)
const formRef = ref()
const fieldNames = { label: 'name', value: 'key', children: 'children' }
const tempTypeStore = useTempTypeStore()
const mediumStore = useMediumTypeStore()
const userStore = useUserStore()
const disableMedia = ref(false)

const notifyToDingTalkBot: () => void = () => {
  const userItem = userStore.options.find((item: any) => item.value === formState.RecommendEmpId)
  if (!userItem)
    return
  const msgArr = [
    `员工推荐建档`,
    `- 新客：${formState.Phone}`,
    `- 推荐登记人：${userItem.label}`,
  ]
  sendMarkdownMessage(msgArr.join('\n\r'))
}

const onSubmit: () => void = () => {
  formRef.value
    .validate()
    .then(async () => {
      if (loading.value)
        return
      const params = {
        RecommendCustId: '',
        RecommendEmpId: formState.RecommendEmpId,
        Phone: formState.Phone,
        Sex: formState.Sex,
        Age: '20',
        CustName: formState.CustName,
        Remark: formState.Remark,
        MediaSourceType: formState.MediaSourceType,
        MediaSource: formState.MediaSource,
        TmpCustRegType: formState.TmpCustRegType,
        PlanRecallEmps: '',
        PlanRecallEmp: formState.CreatedBy,
        CreatedBy: formState.CreatedBy,
        IncomeCapacity: 'IC_LIANGHAO',
        Country: '0',
        Province: '610000',
        City: '610100',
        Area: '',
        DatetimeReg: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      }
      try {
        loading.value = true
        const response = await ReservationTempCustInfoCreate(params)
        if (response.data?.code === 0) {
          const data = JSON.parse(response.data.data)
          let msg = data.message
          if (msg) {
            if (/UQ_TEMP_CUST_INFO_ID_PHONE|电话已存在|唯一|触发Action: <\/b>Create/.test(msg))
              msg = '客户已存在，请勿重复创建'
          }
          else {
            msg = '客户已经创建成功'
            notifyToDingTalkBot()
          }
          showModal(msg)
        }
        else {
          let msg = response.data?.msg
          if (msg && /UQ_TEMP_CUST_INFO_ID_PHONE|电话已存在|唯一|触发Action: <\/b>Create/.test(msg))
            msg = '客户已存在，请勿重复创建'
          else
            msg = msg || '创建错误'
          showModal(msg)
        }
        console.log('response', response)
      }
      catch (e) {
        console.error(e)
        showModal('创建错误')
      }
      cacheParams(params)
      loading.value = false
    })
    .catch((error: any) => {
      console.log('error', error)
    })
}
const CACHE_KEY = '_previous_params_employee'
function cacheParams(params: any) {
  localStorage.setItem(CACHE_KEY, JSON.stringify(params))
}
function getCacheParams() {
  const data: FormState | null = JSON.parse(localStorage.getItem(CACHE_KEY) || '{}')
  if (!data)
    return
  if (data?.RecommendEmpId)
    formState.RecommendEmpId = data.RecommendEmpId

  if (data?.TmpCustRegType)
    formState.TmpCustRegType = data.TmpCustRegType
  if (data?.PlanRecallEmp)
    formState.CreatedBy = data.PlanRecallEmp
  if (data?.CreatedBy)
    formState.CreatedBy = data.CreatedBy
}
const labelCol = { style: { width: '150px' } }

const phoneState = reactive({
  value: '',
  help: '',
  validateStatus: '',
  loading: false,
  list: [],
  disable: false,
})

async function handleInputSearch(searchValue: string) {
  if (phoneState.loading || phoneState.disable)
    return
  if (!searchValue || !/^1[3-9]\d{9}$/.test(searchValue)) {
    initPhoneState('error', '号码错误', false)
    return
  }
  phoneState.list = []
  initPhoneState('validating', '查询中', true)
  try {
    const response = await ReservationTempCustInfoIndex({
      Phone: searchValue,
      currentPage: '1',
    })
    const respData = response.data
    if (respData.code !== 0) {
      initPhoneState('warning', respData.msg)
      return
    }
    let data = response.data?.data.list
    data = data?.map((item: any) => {
      return {
        建档时间: item['建档时间'],
        客户姓名: item['客户姓名'],
        现场客服: item['现场客服'],
        线上客服: item['线上客服'],
      }
    }) || []
    phoneState.list = data
    phoneState.disable = true
    console.log('phoneState.list', phoneState.list)
    if (data.length) {
      initPhoneState('warning', '客户已经建档')
    }
    else {
      formState.Phone = searchValue
      initPhoneState('success', '号码可以建档')
    }
  }
  catch (error: any) {
    console.error(error)
    initPhoneState('error', '查询失败')
  }
}

function initPhoneState(validateStatus = '', help = '', loading = false) {
  phoneState.validateStatus = validateStatus
  phoneState.help = help
  phoneState.loading = loading
}

function handleClearForm() {
  initPhoneState()
  phoneState.disable = false
  phoneState.list = []
  phoneState.value = ''
}

function filterOption(input: string, option: any) {
  return option.label.toLowerCase().includes(input.toLowerCase())
}

function onMediumChange(val: any) {
  formState.MediaSourceType = val[0] || ''
  formState.MediaSource = val[1] || ''
}

const disableCreatedBy = computed(() => {
  const userItem = userStore.options.find((item: any) => item.value === DEFAULT_CREATED_ID)
  return !!userItem
})

function checkMediaExists() {
  const mediaType = mediumStore.options.find((item: any) => item.key === formState.MediaSourceType)
  if (!mediaType?.children.length)
    return false
  const level2 = mediaType.children.find((item: any) => item.key === formState.MediaSource)

  return !!level2
}

onMounted(() => {
  getCacheParams()
  disableMedia.value = !checkMediaExists()
})
</script>

<template>
  <div class="m-auto max-w-200">
    <h1 class="mb-4 text-3xl font-bold">
      👌 员工推荐建档
    </h1>
    <div py-4 />
    <Form ref="formRef" text="left" :rules="formRules" :model="formState" :label-col="labelCol">
      <FormItem label="新客建档查询" :validate-status="phoneState.validateStatus" :help="phoneState.help">
        <InputSearch
          v-model:value="phoneState.value" :disabled="phoneState.disable" :loading="phoneState.loading"
          placeholder="输入新客手机号查询是否建档" enter-button @search="handleInputSearch"
        />
      </FormItem>

      <TheObjectArrayTableShow v-if="phoneState.list.length" :list="phoneState.list" />
      <template v-else-if="phoneState.disable && !phoneState.list.length">
        <FormItem label="客户姓名" name="CustName">
          <Input v-model:value="formState.CustName" placeholder="请输入客户姓名" />
        </FormItem>
        <FormItem label="性别" name="Sex">
          <RadioGroup v-model:value="formState.Sex" placeholder="请选择客户性别">
            <Radio value="1">
              男
            </Radio>
            <Radio value="2">
              女
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem v-if="disableMedia" label="建档媒介" name="media">
          <Cascader
            v-model:value="formState.media" disabled :field-names="fieldNames" :options="mediumStore.options"
            placeholder="请选择客户建档媒介" @change="onMediumChange"
          />
        </FormItem>
        <FormItem label="建档类型" name="TmpCustRegType">
          <Select
            v-model:value="formState.TmpCustRegType" show-search placeholder="选择建档类型"
            :options="tempTypeStore.options" :filter-option="filterOption"
          />
        </FormItem>
        <FormItem v-if="!disableCreatedBy" label="建档人" name="CreatedBy">
          <Select
            v-model:value="formState.CreatedBy"
            show-search
            placeholder="选择员工建档人"
            :options="userStore.options" :filter-option="filterOption"
          />
        </FormItem>
        <FormItem label="推荐人（员工）" name="RecommendEmpId" help="如果搜索不到自己,请钉钉联系 `上官慧玲`">
          <Select
            v-model:value="formState.RecommendEmpId" show-search placeholder="选择员工推荐人"
            :options="userStore.options" :filter-option="filterOption"
          />
        </FormItem>
        <FormItem label="建档备注">
          <Textarea v-model:value="formState.Remark" :rows="4" />
        </FormItem>
      </template>
      <FormItem v-if="phoneState.disable" text-right>
        <Button v-if="!phoneState.list.length" type="primary" :loading="loading" @click="onSubmit">
          创建
        </Button>
        <Button style="margin-left: 10px" @click="handleClearForm">
          清空
        </Button>
      </FormItem>
    </Form>
  </div>
</template>
